package com.chcit.mobile.mvp.receive.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.dialog.DialogPlus;
import com.chcit.custom.view.dialog.ViewHolder;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.SharedPreUtils;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.di.component.DaggerScanPackageComponent;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.common.contract.ScanPackageContract;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.common.presenter.ScanPackagePresenter;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.receive.Entity.AsnLineBean;
import com.chcit.mobile.mvp.receive.Entity.AsnPackageBean;
import com.chcit.mobile.mvp.receive.Entity.AsnResultBean;
import com.chcit.mobile.mvp.receive.adpter.AsnLineAdapter;
import com.chcit.mobile.mvp.receive.adpter.AsnPackageAdapter;
import com.chcit.mobile.mvp.receive.api.QueryListInput;
import com.jakewharton.rxbinding3.widget.RxTextView;
import com.jess.arms.di.component.AppComponent;
import com.xuexiang.xui.utils.SnackbarUtils;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.toast.XToast;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


public class ReceiveBindSearchDetailFragment extends ScanFragment<ScanPackagePresenter> implements ScanPackageContract.View {


    @BindView(R.id.rv_asn_line_list)
    RecyclerView rvAsnLineList;
    @BindView(R.id.tiet_asn_line_no)
    SuperInputEditText tietAsnLineNo;
    //    @BindView(R.id.tv_asn_line_manufacturer)
//    TextView tvAsnLineManufacturer;
//    @BindView(R.id.tv_asn_line_qty)
//    TextView tvAsnLineQty;
    @BindView(R.id.tl_tabs)
    TabLayout tlTabs;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.rv_asn_line_pakcageInfo)
    RecyclerView rvAsnLinePakcageInfo;
    @BindView(R.id.nsv)
    NestedScrollView nsv;
    @BindView(R.id.tv_asn_line_desc)
    TextView tvDesc;
    @BindView(R.id.rb_asn_line_receive)
    RadioButton rbAsnLineReceive;
    @BindView(R.id.rb_asn_line_inspecte)
    RadioButton rbAsnLineInspecte;
    @BindView(R.id.rb_asn_line_reject)
    RadioButton rbAsnLineReject;
    @BindView(R.id.rg_asn_line_groups)
    RadioGroup rgAsnLineGroups;

    TextView tvAsnPackagePackageNo;
    TextView tvAsnPackageProductCode;
    TextView tvAsnPackageLot;
    TextView tvAsnPackageGuaranteeDate;
    TextView tvAsnPackageDesc;
    private TextView productNameLabel;
    Button btAsnPackageCancel;
    Button btAsnPackageOk;
    private AsnLineAdapter mAdapter;
    private AsnPackageAdapter doneAsnPackageAdapter; // 已处理
    private AsnPackageAdapter unAsnPackageAdapter; //未处理
    List<AsnLineBean> asnLineBeanList = new ArrayList<>();
    List<AsnPackageBean> doneAsnPackageBeanList = new ArrayList<>();
    List<AsnPackageBean> unAsnPackageBeanList = new ArrayList<>();
    AsnResultBean asnTask;
    String info = null;
    private Disposable packageNoDisposable;
    private DialogPlus dialog;


    public static ReceiveBindSearchDetailFragment newInstance(AsnResultBean asnResultBean, MenuTypeEnum type) {
        ReceiveBindSearchDetailFragment fragment = new ReceiveBindSearchDetailFragment();
        fragment.asnTask = asnResultBean;
        // fragment.type = type;type
        return fragment;
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        if(dialog.isShowing()){
            return;
        }
        AsnPackageBean asnPackageBean = new AsnPackageBean(barcodeData);
        int position = unAsnPackageBeanList.indexOf(new AsnPackageBean(barcodeData));
        if (position > -1) {
            final AsnPackageBean packageInfo = unAsnPackageBeanList.get(position);
            JSONObject param = new JSONObject();
            JSONArray packageNos = new JSONArray();
            packageNos.add(barcodeData);
            param.put("asnId", asnTask.getAsnId());//
            param.put("packageNo", packageNos);


                switch (rgAsnLineGroups.getCheckedRadioButtonId()){
                    case R.id.rb_asn_line_receive:  //验收模式
                        int finalPosition = position;
                        btAsnPackageOk.setOnClickListener(v -> {
                            doConfirmReceive(param, packageInfo, finalPosition);
                        });
                        btAsnPackageCancel.setOnClickListener(v->{
                            doRejectConfirmReceive(param, packageInfo, finalPosition);
                        });
                        updateDialog(packageInfo);
                        dialog.show();

                        break;
                    case R.id.rb_asn_line_inspecte:  //验视模式

                        btAsnPackageOk.setOnClickListener(v -> {

                            inspecteConfirm(param,packageInfo);
                        });
                        updateDialog(packageInfo);
                        dialog.show();

                        break;
                    case R.id.rb_asn_line_reject:  //拒收收模式
                        doRejectConfirmReceive(param, packageInfo, position);
                        break;
                    case R.id.rb_asn_line_auto:  //自动收货
                        doConfirmReceive(param, packageInfo, position);
                        break;
                }


        } else if((position= doneAsnPackageBeanList.indexOf(asnPackageBean))>-1){
              doConfirmReTaskLine(doneAsnPackageBeanList.get(position), position);

        }else {
            XToast.error(mContext, "该包装不合法！").show();
        }
    }



    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerScanPackageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_asn_package_line, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        info = getResources().getString(R.string.asn_task_label);
        initRecyclerView();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showMessage(@NonNull String message) {

    }


    private void initRecyclerView() {
        initTaskLineRecycleView();
        initUnRecycleView();
        initDoneRecycleView();



    }

    private void initEvent() {
        tlTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                getDataList();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        packageNoDisposable = RxTextView.editorActionEvents(tietAsnLineNo)
                .subscribe(textViewEditorActionEvent -> {
                    String text = Objects.requireNonNull(tietAsnLineNo.getText()).toString();
                    if ((textViewEditorActionEvent.getActionId() == KeyEvent.KEYCODE_CALL||textViewEditorActionEvent.getActionId() == KeyEvent.KEYCODE_ENDCALL )&& !text.isEmpty()) {
                        onBarcodeEventSuccess(text);
                    }
                });

        rgAsnLineGroups.setOnCheckedChangeListener((radioGroup, i) -> {
            SharedPreUtils.getInstance().putInt(DataKeys.ASN_AUTO_MODE.name(),i);
            switch (i){
                case  R.id.rb_asn_line_receive:  //验收模式
                    btAsnPackageOk.setText("收货");
                    btAsnPackageCancel.setVisibility(View.VISIBLE);

                    break;
                case  R.id.rb_asn_line_inspecte:  //验视模式
                    btAsnPackageOk.setText("验视");
                    btAsnPackageCancel.setVisibility(View.GONE);
//                    SharedPreUtils.getInstance().putInt(DataKeys.ASN_AUTO_MODE.name(),R.id.rb_asn_line_inspecte);
                    break;
                case R.id.rb_asn_line_reject:  //自动拒收
//                    SharedPreUtils.getInstance().putInt(DataKeys.ASN_AUTO_MODE.name(),R.id.rb_asn_line_reject);
                    break;
                case R.id.rb_asn_line_auto:  //自动收货
//                    SharedPreUtils.getInstance().putInt(DataKeys.ASN_AUTO_MODE.name(),R.id.rb_asn_line_auto);
                    break;
            }
        });
        rgAsnLineGroups.check(SharedPreUtils.getInstance().getInt(DataKeys.ASN_AUTO_MODE.name(),R.id.rb_asn_line_receive));

    }

    private void initTaskLineRecycleView() {
        mAdapter = new AsnLineAdapter(asnLineBeanList);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        rvAsnLineList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvAsnLineList.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, 5, R.color.White));
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position >= 0 && adapter.getData().size() > position) {
//                    mAdapter.setCheckedPosition(position);
//                    mRecipeBean = (AsnLineBean) adapter.getData().get(position);
//                    if (tlTabs.getSelectedTabPosition() == 1) {
//                        if(mRecipeBean.getLocatorValue()!= null){
//                            tietRealLocator.setText(mRecipeBean.getLocatorValue());
//                        }
//                    } else {
//                        tietPointLocator.setText("");
//
//                    }
//                    updateClickItemData();
            }

        });
        rvAsnLineList.setAdapter(mAdapter);
        getLineTaskList();
    }
    private void getLineTaskList(){
        QueryListInput.Builder builder = new QueryListInput.Builder()
                .asnNo(asnTask.getAsnNo());
        mPresenter.queryAsnLineTask(builder.build(), list -> {
            mAdapter.getData().clear();
            mAdapter.addData(list);
            updateDesc();
        });
    }
    //未处理
    private void initUnRecycleView() {
        unAsnPackageAdapter = new AsnPackageAdapter(unAsnPackageBeanList);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        rvAsnLinePakcageInfo.setLayoutManager(new LinearLayoutManager(getContext()));
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        unAsnPackageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position >= 0 && adapter.getData().size() > position) {
                    unAsnPackageAdapter.setCheckedPosition(position);
                    tietAsnLineNo.setText(unAsnPackageBeanList.get(position).getPackageNo());
                }

            }
        });
        rvAsnLinePakcageInfo.setAdapter(unAsnPackageAdapter);
        tlTabs.getTabAt(0).select();
        getDataList();
    }

    //已处理
    private void initDoneRecycleView() {
        doneAsnPackageAdapter = new AsnPackageAdapter(doneAsnPackageBeanList);
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        doneAsnPackageAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position >= 0 && adapter.getData().size() > position) {
                doneAsnPackageAdapter.setCheckedPosition(position);
                tietAsnLineNo.setText(doneAsnPackageBeanList.get(position).getPackageNo());

            }

        });
    }

    public void getDataList() {
        switch (tlTabs.getSelectedTabPosition()) {
            case 0:
                mPresenter.queryAsnPackageList(
                        new QueryListInput.Builder()
                                .asnId(String.valueOf(asnTask.getAsnId()))
                                .checkStatus("N")
                                .build(),
                        list -> {
                            unAsnPackageAdapter.getData().clear();
                            unAsnPackageAdapter.addData(list);
                            rvAsnLinePakcageInfo.setAdapter(unAsnPackageAdapter);

                        }

                );
                break;
            case 1:
                mPresenter.queryAsnPackageList(
                        new QueryListInput.Builder()
                                .asnId(String.valueOf(asnTask.getAsnId()))
                                .checkStatus("Y")
                                .build(),
                        list -> {
                            doneAsnPackageAdapter.getData().clear();
                            doneAsnPackageAdapter.addData(list);
                            rvAsnLinePakcageInfo.setAdapter(doneAsnPackageAdapter);
                        }

                );
                break;
        }
    }

    //验收确认方法调用
    private void doConfirmReceive(JSONObject data, AsnPackageBean packageInfo, int position) {
        mPresenter.checkAsnPackageRecieve(data, () -> {
            dialog.dismiss();
            if(unAsnPackageBeanList.size() == 0 ){
                SnackbarUtils.Short(getView(), "该任务已完成！即将返回上一个页面")
                        .info()
                        .setCallback(new Snackbar.Callback() {
                            @Override
                            public void onDismissed(Snackbar snackbar, int event) {
                                super.onDismissed(snackbar, event);
                                setFragmentResult(-3,null);
                                pop();
                            }

                            @Override
                            public void onShown(Snackbar snackbar) {
                                super.onShown(snackbar);

                            }
                        })
                        .gravityFrameLayout(Gravity.CENTER).show();

            }else {
                getLineTaskList();
                XToast.success(mContext, "验收成功！").show();

            }


        });
    }

    //验收场合拒收方法调用
    private void doRejectConfirmReceive(JSONObject data, AsnPackageBean packageInfo, int position) {
        mPresenter.queryListData(new Consumer<List<Statu>>() {
            int i = 0;

            @Override
            public void accept(List<Statu> status) throws Exception {
                new MaterialDialog.Builder(mContext)
                        .title("拒收原因")
                        .items(status)
                        .itemsCallbackSingleChoice(i, (dialog, itemView, which, text) -> {
                            i = which;
                            // {asnId:"1212",asnLineId:12123,rejectReason:"test",packageNo:["2323","232323dfdf"]}}
                            // JSONObject data = new JSONObject();
                            data.put("asnId", asnTask.getAsnId());//
                            data.put("rejectReason", status.get(i).getId());
                            JSONArray packageNos = new JSONArray();
                            packageNos.add(packageInfo.getPackageNo());
                            data.put("packageNo", packageNos);
                            mPresenter.rejectAsnPackage(data, () -> {
                                doneAsnPackageAdapter.addData(packageInfo);
                                unAsnPackageAdapter.remove(position);
                                int i = asnLineBeanList.indexOf(new AsnLineBean(
                                        packageInfo.getProductId(),
                                        packageInfo.getProductName(),
                                        packageInfo.getProductCode()
                                ));
                                if (i > -1) {
                                    asnLineBeanList.get(i).setQtyCheckLeft(asnLineBeanList.get(i).getQtyCheckLeft().subtract(packageInfo.getQty()));
                                    asnLineBeanList.get(i).setPackageCountCheckLeft(asnLineBeanList.get(i).getPackageCountCheckLeft().subtract(BigDecimal.ONE));
                                    asnLineBeanList.get(i).setQtyReceived(asnLineBeanList.get(i).getQtyReceived().add(packageInfo.getQty()));
                                    asnLineBeanList.get(i).setPackageCountRejected(asnLineBeanList.get(i).getPackageCountRejected().add(BigDecimal.ONE));
                                }
                                XToast.success(mContext, "拒收成功！").show();
                                updateDesc();

                            });
                            return true;
                        }).neutralText("取消")
                        .positiveText("确认")
                        .build()
                        .show();
            }
        });
    }
    public void doConfirmReTaskLine( AsnPackageBean packageInfo, int position){
        new MaterialDialog.Builder(mContext)
                .title("提示")
                .content("该包装已验收成功，是否撤销验收")
                .positiveText("取消")
                .negativeText("确认")
                .onNegative((d,which)->{
//                    JSONArray packageNoList = new JSONArray();
//                    packageNoList.add();
                    mPresenter.reCheckTaskLine(Arrays.asList(packageInfo.getPackageNo()),String.valueOf(asnTask.getAsnId()),()->{

//                        doneAsnPackageAdapter.remove(position);
//                        unAsnPackageAdapter.addData(packageInfo);
//                        int i = asnLineBeanList.indexOf(new AsnLineBean(
//                                packageInfo.getProductId(),
//                                packageInfo.getProductName(),
//                                packageInfo.getProductCode()
//                        ));
//                        if (i > -1) {
//                            asnLineBeanList.get(i).setQtyCheckLeft(asnLineBeanList.get(i).getQtyCheckLeft().add(packageInfo.getQty()));
//                            asnLineBeanList.get(i).setPackageCountCheckLeft(asnLineBeanList.get(i).getPackageCountCheckLeft().add(BigDecimal.ONE));
//                            asnLineBeanList.get(i).setQtyReceived(asnLineBeanList.get(i).getQtyReceived().subtract(packageInfo.getQty()));
//                            asnLineBeanList.get(i).setPackageCountRejected(asnLineBeanList.get(i).getPackageCountRejected().subtract(BigDecimal.ONE));
//                        }
                        XToast.success(mContext, "撤销成功！").show();
                        getLineTaskList();
                    });
                })
                .onPositive((d,which)->{
                    d.dismiss();
                }).show();
    }
    //开箱验视确认方法调用
    private void inspecteConfirm(JSONObject data,AsnPackageBean packageInfo) {
        JSONArray packageNos = new JSONArray();
        packageNos.add(packageInfo.getPackageNo());
        data.put("packageNo", packageNos);
        // {asnId:"1212",asnLineId:12123,locatorId:"1212",packageNo:["2323","232323dfdf"]}
        assert mPresenter != null;
        mPresenter.inspectePackageRecieve(data, () -> {
            dialog.dismiss();
            XToast.success(mContext, "验视成功！").show();
        });
    }

    //共%1$d个品种，到货%2$d包/%3$d,待验收%4$d包/%5$d

    private void updateDesc() {

        BigDecimal arriveNumber = BigDecimal.ZERO;
        ;
        BigDecimal arrivePackage = BigDecimal.ZERO;
        BigDecimal checkNumber = BigDecimal.ZERO;
        ;
        BigDecimal checkPackage = BigDecimal.ZERO;
        BigDecimal rejectNumber = BigDecimal.ZERO;
        BigDecimal rejectPackage = BigDecimal.ZERO;
        for (AsnLineBean alb : asnLineBeanList) {
            arriveNumber = arriveNumber.add(alb.getQtyArrived());
            arrivePackage = arrivePackage.add(alb.getPackageCountArrived());
            checkNumber = checkNumber.add(alb.getQtyCheckLeft());
            checkPackage = checkPackage.add(alb.getPackageCountCheckLeft());
            rejectPackage = rejectPackage.add(alb.getPackageCountRejected());
            rejectNumber = rejectNumber.add(alb.getQtyRejected());
        }
        tvDesc.setText(String.format(info, asnLineBeanList.size(), arrivePackage.toString(),
                arriveNumber.toString(), checkPackage.toString(), checkNumber.toString(),
                rejectPackage.toString(), rejectNumber.toString()
        ));
    }

    private void initDialog() {
        TextView title =  new TextView(mContext);
        title.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        title.setTextSize(18);
        title.setAllCaps(true);
        title.setGravity(Gravity.CENTER);
        title.setText("扫码详情");
        dialog = DialogPlus.newDialog(getContext())
                .setHeader(title)
                .setContentHolder(new ViewHolder(R.layout.dialog_asn_task_package))
                //.setExpanded(true)  // This will enable the expand feature, (similar to android L share dialog)
                .setGravity(Gravity.BOTTOM | Gravity.END)
                .setCancelable(true)
                .create();
        productNameLabel = dialog.findViewById(R.id.tv_asn_package_productName);
        tvAsnPackagePackageNo = dialog.findViewById(R.id.tv_asn_package_packageNo);
        tvAsnPackageProductCode = dialog.findViewById(R.id.tv_asn_package_productCode);
        tvAsnPackageLot = dialog.findViewById(R.id.tv_asn_package_lot);
        tvAsnPackageGuaranteeDate = dialog.findViewById(R.id.tv_asn_package_guaranteeDate);
        tvAsnPackageDesc = dialog.findViewById(R.id.tv_asn_package_desc);
        btAsnPackageCancel = dialog.findViewById(R.id.bt_asn_package_cancel);
        btAsnPackageOk = dialog.findViewById(R.id.bt_asn_package_ok);


        btAsnPackageCancel.setOnClickListener(v -> {
            dialog.dismiss();
        });

    }
    private void updateDialog(AsnPackageBean packageBean) {
        //tvDialogDesc.setText(packageBean.get);
        tvAsnPackagePackageNo.setText(packageBean.getPackageNo());
        tvAsnPackageProductCode.setText(packageBean.getProductCode());
        tvAsnPackageLot.setText(packageBean.getLot());
        tvAsnPackageGuaranteeDate.setText(packageBean.getGuaranteeDate());
         productNameLabel.setText(packageBean.getProductName());
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (packageNoDisposable
                != null) {
            packageNoDisposable.dispose();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initDialog();
        initEvent();
    }
}
